package javacommon.authority.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javacommon.authority.controller.MenuController;
import javacommon.authority.model.Menu;
import javacommon.authority.model.User;
import javacommon.authority.model.UserRole;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class ShiroDbRealm extends AuthorizingRealm {
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// 因为非正常退出，即没有显式调用 SecurityUtils.getSubject().logout()
		// (可能是关闭浏览器，或超时)，但此时缓存依旧存在(principals)，所以会自己跑到授权方法里。
		if (!SecurityUtils.getSubject().isAuthenticated()) {
			doClearCache(principals);
			SecurityUtils.getSubject().logout();
			return null;
		}
		String loginName = (String) principals.fromRealm(getName()).iterator()
				.next();
		User user = User.dao.findFirstByAccount(loginName);
		if (user != null) {
			// 添加角色信息
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			Set<String> roleNameSet = new HashSet<>();
			for (UserRole userRole : user.getRoles()) {
				roleNameSet.add(userRole.getRole().getStr("code"));
			}
			info.addRoles(roleNameSet);
			//添加权限信息
			List<Menu> menus = user.getMenus(null);// 获取全部菜单
			Set<String> menuPageurlSet = new HashSet<>();
			for (Menu menu : menus) {
				String pageurl = menu.getStr("pageurl");
				if (!StringUtils.isBlank(pageurl)) {
					menuPageurlSet.add(pageurl);
				}
			}
			info.addStringPermissions(menuPageurlSet);
			return info;

		} else {
			return null;
		}
	}

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = User.dao.findFirstByAccount(token.getUsername());
		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}
		if (user.get("state").equals("否")) {// 账号被冻结
			throw new LockedAccountException(" USER Freeze");
		}
		return new SimpleAuthenticationInfo(user.get("account"),
				user.get("password"), this.getName());
	}

}
